package com.demo.steammanagement.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.steammanagement.common.DateUtils;
import com.demo.steammanagement.mapper.UsersMapper;
import com.demo.steammanagement.model.dto.UserDto;
import com.demo.steammanagement.model.entity.Users;
import com.demo.steammanagement.model.vo.UserVO;
import com.demo.steammanagement.service.IUsersService;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author dayu
 * @since 2024-11-17
 */
@Service
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {
  @Autowired
  private UsersMapper userMapper;
  @Autowired
  private BCryptPasswordEncoder bCryptPasswordEncoder;

  @Override
  public IPage<Users> getUsersByPage(int pageNum, int pageSize, String queryString) {
    // 创建分页对象
    Page<Users> page = new Page<>(pageNum, pageSize);

    // 创建 Lambda 查询包装器
    LambdaQueryWrapper<Users> queryWrapper = Wrappers.lambdaQuery();

    // 设置模糊查询条件
    if (queryString != null && !queryString.trim().isEmpty()) {
      queryWrapper.like(Users::getAccount, queryString);
    }

    // 执行查询
    IPage<Users> usersIPage = this.page(page, queryWrapper);

    // 返回结果
    return usersIPage;
  }

  @Override
  public void changePassword(String pwd) {
    String encodedPassword = new BCryptPasswordEncoder().encode(pwd);
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    LambdaUpdateWrapper<Users> wrapper = new LambdaUpdateWrapper<>();
    wrapper.eq(Users::getAccount,username);
    wrapper.set(Users::getPassword, encodedPassword);
    this.update(null, wrapper);
  }

  @Override
  public Users getUserByEmail(String email) {
    LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Users::getEmail, email);
    queryWrapper.last("limit 1");
    Users user = userMapper.selectOne(queryWrapper);
    return user;
  }


  @Override
  public Users getUserByUsername(String username) {
    LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Users::getAccount, username);
    queryWrapper.last("limit 1");
    Users user = userMapper.selectOne(queryWrapper);
    return user;
  }

  @Override
  public boolean existsByUsername(String username) {
    LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Users::getAccount, username);
    queryWrapper.last("limit 1");
    Users user = userMapper.selectOne(queryWrapper);
    if (user != null) {
      return true;
    }
    return false;// 用户不存在
  }
  @Override
  public boolean existsByEmail(String email) {
    LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Users::getEmail, email);
    queryWrapper.last("limit 1");
    Users user = userMapper.selectOne(queryWrapper);
    if (user != null) {
      return true;
    }
    return false;// 用户不存在
  }


  @Override
  public boolean registerUser(UserDto vo) {
    // 加密密码
    String encodedPassword = bCryptPasswordEncoder.encode(vo.getPassword());

    // 创建新用户并保存
    Users newUser = new Users();
    newUser.setAccount(vo.getAccount());
    newUser.setEmail(vo.getEmail());
    newUser.setPassword(encodedPassword);
    newUser.setStatus(1);
    save(newUser);
    return true;
  }

  @Override
  public void updateAccountExpirationDate() {
	  try {
		  LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<Users>()
		            .lt(Users::getAccountExpirationDate, LocalDateTime.now()) 
		  			.ne(Users::getUserRole, 1);
		  			
		  List<Users> expiredUsers = userMapper.selectList(queryWrapper);
		  
		  if (CollectionUtils.isEmpty(expiredUsers)) {
			  return;
		  }
		  
		  for (Users user : expiredUsers) {
			  if (user.getNormalValidity() > 0) {
				  user.setUserRole(String.valueOf(3));
				  user.setAccountExpirationDate(DateUtils.dataPlus(user.getAccountExpirationDate(), user.getNormalValidity(), true));
				  user.setNormalValidity(0L);
			  } else {
				  user.setUserRole(String.valueOf(2));
			  }
			  userMapper.updateById(user);
		  }
		  
	  } catch (Exception e) {
		  log.info(e.toString());
	  }
  }

  @Override
  public void retrievePassword(UserVO vo) {
    LambdaUpdateWrapper<Users> updateWrapper = new LambdaUpdateWrapper<>();
    updateWrapper.eq(Users::getEmail, vo.getEmail())
            .eq(Users::getAccount, vo.getAccount())
            .set(Users::getPassword, bCryptPasswordEncoder.encode(vo.getConfirmPassword()));
    userMapper.update(updateWrapper);
  }

  @Override
  public Users getUserByEmailAndAccount(String email, String account) {
    return userMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getEmail, email)
            .eq(Users::getAccount, account)
    );
  }
}
